<template>
  <div ref="chart" style="width: 100%; height: 350px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import { listFinance } from '@/api/Information/finance';

export default {
  mounted() {
    this.initChart();
  },
  methods: {
    async initChart() {
      // 获取财务数据
      const response = await listFinance({
        pageNum: 1,
        pageSize: 1000 // 获取全部数据
      });

      // 数据处理
      const monthlyData = this.processData(response.rows);

      // 初始化图表
      const chart = echarts.init(this.$refs.chart);
      chart.setOption(this.getChartOption(monthlyData));
    },

    processData(data) {
      // 按年份和月份聚合数据
      const monthlyMap = new Map();

      data.forEach(item => {
        const date = new Date(item.createTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零，格式化为 "01", "02" 等
        const key = `${year}-${month}`; // 组合成 "2024-05" 格式的键

        if (!monthlyMap.has(key)) {
          monthlyMap.set(key, 0);
        }
        monthlyMap.set(key, monthlyMap.get(key) + Number(item.amount));
      });

      // 转换为排序后的数组
      return Array.from(monthlyMap).sort((a, b) => {
        // 按年份和月份排序
        return a[0].localeCompare(b[0]);
      });
    },

    getChartOption(processedData) {
      return {
        title: { text: '月度物业费收支趋势' },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c}元'
        },
        xAxis: {
          type: 'category',
          data: processedData.map(item => item[0]) // X 轴显示完整的年份和月份
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        series: [{
          name: '总金额',
          type: 'line',
          data: processedData.map(item => item[1]),
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64,158,255,0.6)' },
              { offset: 1, color: 'rgba(64,158,255,0.02)' }
            ])
          }
        }]
      };
    }
  },
  watch: {
    // 当数据变化时自动刷新图表
    '$route': 'initChart'
  }
};
</script>
